﻿// -----------------------------------------------------------------------
// <copyright file="StreamWriterExtensions.cs" company="Zen Design Corp">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Zen.BlackBerry.Common
{
	using System;
	using System.IO;

	/// <summary>
	/// Contains extensions to the <see cref="StreamWriter"/> class.
	/// </summary>
	public static class StreamWriterExtensions
	{
		/// <summary>
		/// Writes the raw buffer bytes directly to the underlying stream.
		/// </summary>
		/// <param name="writer">The writer.</param>
		/// <param name="buffer">The buffer.</param>
		/// <param name="offset">The offset.</param>
		/// <param name="length">The length.</param>
		public static void WriteRaw(
			this StreamWriter writer, byte[] buffer, int offset, int length)
		{
			// Flush our writes as necessary
			if (!writer.AutoFlush)
			{
				writer.Flush();
			}

			// Write directly to underlying stream
			writer.BaseStream.Write(buffer, offset, length);
		}

		/// <summary>
		/// Writes the raw buffer as a base64 encoded string optionally
		/// splitting the string every <paramref name="splitLineAtCol"/>
		/// characters and optionally terminating the sequence with a
		/// line-feed.
		/// </summary>
		/// <param name="writer">The writer.</param>
		/// <param name="buffer">The buffer.</param>
		/// <param name="offset">The offset.</param>
		/// <param name="length">The length.</param>
		/// <param name="splitLineAtCol">
		/// Specify 0 to disable string splitting, specify a value > 0 to force
		/// the base64 string to be split into splitLineAtCol chunks.
		/// </param>
		/// <param name="appendLineFeed">
		/// if set to <c>true</c> a line-feed will be appended to the final
		/// block being written.
		/// </param>
		public static void WriteRawBase64(
			this StreamWriter writer,
			byte[] buffer,
			int offset,
			int length,
			int splitLineAtCol = 76,
			bool appendLineFeed = true)
		{
			string content = Convert.ToBase64String(buffer, offset, length);
			if (splitLineAtCol < 1)
			{
				if (appendLineFeed)
				{
					writer.WriteLine(content);
				}
				else
				{
					writer.Write(content);
				}
			}
			else
			{
				while (content.Length > splitLineAtCol)
				{
					string segment = content.Substring(0, splitLineAtCol);
					content = content.Substring(splitLineAtCol);

					writer.WriteLine(segment);
				}

				if (!string.IsNullOrEmpty(content))
				{
					if (appendLineFeed)
					{
						writer.WriteLine(content);
					}
					else
					{
						writer.Write(content);
					}
				}
			}
		}
	}
}
